home *** CD-ROM | disk | FTP | other *** search
- Path: crl.crl.com!not-for-mail
- From: bobfry@crl.com (Robert Fry)
- Newsgroups: comp.lang.c
- Subject: Re: Help with gettng 2 chars into an integer!
- Date: 11 Jan 1996 08:32:30 -0800
- Organization: CRL Dialup Internet Access
- Message-ID: <4d3e2u$1hr@crl.crl.com>
- References: <4d2eh1$7pm@usc.edu>
- NNTP-Posting-Host: crl.com
-
- wawda@scf.usc.edu (Abu Wawda) writes:
-
- >Hi. I can't seem to figure out how to do this. Basically I have to chars that
- >I want to put into a 2-byte integer. It seems easy at first, but I can't seem
- >to figure out to do it with the bit-fidling operators (shifting or masking).
- >Simple put, I'd like to do:
-
- > char a,b;
- > int c;
-
- > a = 'A';
- > b = 'B';
- > c = ? /* the first byte in c should contain the value of a, and the
- >second byte should contain the value of b */
-
- Assuming chars are 8 bits, and assuming sizeof( int) >= 2 * sizeof( char),
- then you can use the following (note that it may be incorrect with
- respect to the endianness of your CPU, and is clearly not portable):
-
- c = (( a << 8) & 0x0FF00) | ( b & 0x00FF);
-
- This will work. You can also put a and b into a union that contains an
- array of 2 characters and an int. I'm not sure how to make the structure
- independent of endianness, but someone should have an idea if that's an
- issue for you.
-
- I've used both, depending on the needs of the moment.
-
- Bob
-